/*
 *
 *      Copyright (c) 2018-2025, cloud All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: cloud
 *
 */

package com.fuyao.cloud.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuyao.cloud.admin.api.dto.UserDTO;
import com.fuyao.cloud.admin.api.dto.UserInfo;
import com.fuyao.cloud.admin.api.dto.UserSsoDTO;
import com.fuyao.cloud.admin.api.entity.*;
import com.fuyao.cloud.admin.api.vo.UserExcelVO;
import com.fuyao.cloud.admin.api.vo.UserVO;
import com.fuyao.cloud.admin.mapper.SysUserMapper;
import com.fuyao.cloud.admin.mapper.SysUserPostMapper;
import com.fuyao.cloud.admin.mapper.SysUserinfoMapper;
import com.fuyao.cloud.admin.message.service.SystemMessageRecordService;
import com.fuyao.cloud.admin.service.*;
import com.fuyao.cloud.common.core.constant.CacheConstants;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.exception.ErrorCodes;
import com.fuyao.cloud.common.core.util.MsgUtils;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.datascope.DataScope;
import com.fuyao.cloud.common.data.resolver.ParamResolver;
import com.fuyao.cloud.common.excel.vo.ErrorMessage;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author cloud
 * @date 2017/10/31
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	private final SysMenuService sysMenuService;

	private final SysRoleService sysRoleService;

	private final SysDeptService sysDeptService;

	private final SysUserRoleService sysUserRoleService;

	private final SysUserPostMapper sysUserPostMapper;

	private final SysUserinfoMapper userinfoMapper;

	private final SysUserinfoService userinfoService;

	private final SystemMessageRecordService systemMessageRecordService;



	/**
	 * 保存用户信息
	 *  userDto DTO 对象
	 * @return success/fail
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveUser(UserDTO userDto,SysUserinfo userinfo) {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(userDto, sysUser);
		sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
		sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
		baseMapper.insert(sysUser);
		userinfo.setUserId(sysUser.getUserId());
 		this.userinfoMapper.insert(userinfo);
		List<SysUserRole> userRoleList = userDto.getRole().stream().map(roleId -> {
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleId);
			return userRole;
		}).collect(Collectors.toList());
		return sysUserRoleService.saveBatch(userRoleList);
	}

	/**
	 * 保存用户信息
	 *  userDto DTO 对象
	 * @return success/fail
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveUser(UserDTO userDto) {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(userDto, sysUser);
		sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
		sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
		baseMapper.insert(sysUser);
		// 保存用户详细信息
		userinfoService.saveOrUpdateUserinfo(sysUser);
		// 保存用户岗位信息
		Optional.ofNullable(userDto.getPost()).ifPresent(posts -> {
			posts.stream().map(postId -> {
				SysUserPost userPost = new SysUserPost();
				userPost.setUserId(sysUser.getUserId());
				userPost.setPostId(postId);
				return userPost;
			}).forEach(sysUserPostMapper::insert);
		});

		// 如果角色为空，赋默认角色
		if (CollUtil.isEmpty(userDto.getRole())) {
			// 获取默认角色编码
			String defaultRole = ParamResolver.getStr("USER_DEFAULT_ROLE");
			// 默认角色
			SysRole sysRole = sysRoleService
					.getOne(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getRoleCode, defaultRole));
			userDto.setRole(Collections.singletonList(sysRole.getRoleId()));
		}

		List<SysUserRole> userRoleList = userDto.getRole().stream().map(roleId -> {
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleId);
			return userRole;
		}).collect(Collectors.toList());
		return sysUserRoleService.saveBatch(userRoleList);
	}

	/**
	 * 通过查用户的全部信息
	 * @param sysUser 用户
	 * @return
	 */
	@Override
	public UserInfo findUserInfo(SysUser sysUser) {
		UserInfo userInfo = new UserInfo();
		// 设置部门名称。
		SysDept sysDept = this.sysDeptService.getById(sysUser.getDeptId());
		sysUser.setDeptName(sysDept.getFullName());
		userInfo.setSysUser(sysUser);
		// 设置角色列表 （ID）
		List<Long> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId()).stream().map(SysRole::getRoleId)
				.collect(Collectors.toList());
		userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class));

		// 设置权限列表（menu.permission）
		Set<String> permissions = new HashSet<>();
		roleIds.forEach(roleId -> {
			List<String> permissionList = sysMenuService.findMenuByRoleId(roleId).stream()
					.filter(menu -> StrUtil.isNotEmpty(menu.getPermission())).map(SysMenu::getPermission)
					.collect(Collectors.toList());
			permissions.addAll(permissionList);
		});
		userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));

		// 详细信息
		SysUserinfo info = userinfoMapper.selectOne(Wrappers.<SysUserinfo>lambdaQuery().eq(SysUserinfo::getUserId,sysUser.getUserId()));
		userInfo.setInfos(info);
		return userInfo;
	}

	/**
	 * 分页查询用户信息（含有角色信息）
	 * @param page 分页对象
	 * @param userDTO 参数列表
	 * @return
	 */
	@Override
	public IPage getUsersWithRolePage(Page page, UserDTO userDTO) {
		return baseMapper.getUserVosPage(page, userDTO, DataScope.of());
	}

	/**
	 * 选择userinfo表中没有user的信息
	 * @param page 分页对象
	 * @param userDTO 参数列表
	 * @return
	 */
	@Override
	public IPage getNotUserInfoSelectPage(Page page, UserDTO userDTO) {
		return baseMapper.getNotUserInfoSelectPage(page, userDTO, new DataScope());
	}

	/**
	 * 选择user和userinfo共同数据信息
	 * @param page 分页对象
	 * @param userDTO 参数列表
	 * @return
	 */
	@Override
	public IPage getUserInfoSelectPage(Page page, UserDTO userDTO) {
		return baseMapper.getUserInfoSelectPage(page, userDTO, new DataScope());
	}

	/**
	 * 通过ID查询用户信息
	 * @param id 用户ID
	 * @return 用户信息
	 */
	@Override
	public UserVO selectUserVoById(Long id) {
		return baseMapper.getUserVoById(id);
	}

	@Override
	public UserVO getUserVoAndDeptById(Long id) {
		return baseMapper.getUserVoAndDeptById(id);
	}

	/**
	 * 通过id查询用户信息
	 * @param id
	 * @return
	 */
	 @Override
	 public UserSsoDTO getUserSsoDtoById(Long id){
		return baseMapper.getUserSsoDtoById(id);
	}

	/**
	 * 删除用户
	 * @param sysUser 用户
	 * @return Boolean
	 */
	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#sysUser.username")
	public Boolean deleteUserById(SysUser sysUser) {
		sysUserRoleService.deleteByUserId(sysUser.getUserId());
		userinfoMapper.delete(Wrappers.<SysUserinfo>query().lambda().eq(SysUserinfo::getUserId,sysUser.getUserId()));
		this.removeById(sysUser.getUserId());
		return Boolean.TRUE;
	}

	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userDto.username")
	public R<Boolean> updateUserInfo(UserDTO userDto) {
		UserVO userVO = baseMapper.getUserVoByUsername(userDto.getUsername());
		if (!ENCODER.matches(userDto.getPassword(), userVO.getPassword())) {
			log.info("原密码错误，修改个人信息失败:{}", userDto.getUsername());
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_UPDATE_PASSWORDERROR));
		}

		SysUser sysUser = new SysUser();
		if (StrUtil.isNotBlank(userDto.getNewpassword1())) {
			sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
		}
		// 记录修改密码
		if(!userDto.getPassword().equals(userDto.getNewpassword1())){
			sysUser.setUpdatePasswordDateTime(LocalDateTime.now());
		}
		sysUser.setPhone(userDto.getPhone());
		sysUser.setUserId(userVO.getUserId());
		sysUser.setAvatar(userDto.getAvatar());
		sysUser.setNickname(userDto.getNickname());
		sysUser.setName(userDto.getName());
		sysUser.setEmail(userDto.getEmail());
		// 保存用户详细信息
		userinfoService.saveOrUpdateUserinfo(sysUser);
		return R.ok(this.updateById(sysUser));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#userDto.username")
	public Boolean updateUser(UserDTO userDto) {
		SysUser sysUser = new SysUser();
		BeanUtils.copyProperties(userDto, sysUser);
		sysUser.setUpdateTime(LocalDateTime.now());

		if (StrUtil.isNotBlank(userDto.getPassword())) {
			sysUser.setPassword(ENCODER.encode(userDto.getPassword()));
		}
		UserVO userVO = baseMapper.getUserVoByUsername(userDto.getUsername());
		if (!ENCODER.matches(userDto.getPassword(), userVO.getPassword())) {
			sysUser.setUpdatePasswordDateTime(LocalDateTime.now());
		}
		this.updateById(sysUser);
		// 保存用户详细信息
		userinfoService.saveOrUpdateUserinfo(sysUser);

		sysUserRoleService
				.remove(Wrappers.<SysUserRole>update().lambda().eq(SysUserRole::getUserId, userDto.getUserId()));
		userDto.getRole().forEach(roleId -> {
			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(sysUser.getUserId());
			userRole.setRoleId(roleId);
			userRole.insert();
		});
		sysUserPostMapper.delete(Wrappers.<SysUserPost>lambdaQuery().eq(SysUserPost::getUserId, userDto.getUserId()));
		userDto.getPost().forEach(postId -> {
			SysUserPost userPost = new SysUserPost();
			userPost.setUserId(sysUser.getUserId());
			userPost.setPostId(postId);
			userPost.insert();
		});
		return Boolean.TRUE;
	}

	/**
	 * 查询上级部门的用户信息
	 * @param username 用户名
	 * @return R
	 */
	@Override
	public List<SysUser> listAncestorUsers(String username) {
		SysUser sysUser = this.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));

		SysDept sysDept = sysDeptService.getById(sysUser.getDeptId());
		if (sysDept == null) {
			return null;
		}
		Long parentId = (0 == sysDept.getParentId() ? sysDept.getDeptId():sysDept.getParentId());
		return this.list(Wrappers.<SysUser>query().lambda().eq(SysUser::getDeptId, parentId));
	}

	@Override
	public SysUser getUserByUsername(String username){
		return this.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username), false);
	}

	/**
	 * 查询全部的用户
	 * @param userDTO 查询条件
	 * @return list
	 */
	@Override
	public List<UserExcelVO> listUser(UserDTO userDTO) {
		// 根据数据权限查询全部的用户信息
		List<UserVO> voList = baseMapper.selectVoListByScope(userDTO, DataScope.of());
		// 转换成execl 对象输出
		List<UserExcelVO> userExcelVOList = voList.stream().map(userVO -> {
			UserExcelVO excelVO = new UserExcelVO();
			BeanUtils.copyProperties(userVO, excelVO);
			String roleNameList = userVO.getRoleList().stream().map(SysRole::getRoleName)
					.collect(Collectors.joining(StrUtil.COMMA));
			excelVO.setRoleNameList(roleNameList);
			return excelVO;
		}).collect(Collectors.toList());
		return userExcelVOList;
	}

	/**
	 * excel 导入用户, 插入正确的 错误的提示行号
	 * @param excelVOList excel 列表数据
	 * @param bindingResult 错误数据
	 * @return ok fail
	 */
	@Override
	public R importUser(List<UserExcelVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

		// 个性化校验逻辑
		List<SysUser> userList = this.list();
		List<SysDept> deptList = sysDeptService.list();
		List<SysRole> roleList = sysRoleService.list();
		// 获取人员编号
		List<String> personNumList= this.userinfoMapper.findPersonNumAll();
		// 获取所有身份证号
		List<String> idNumberList = this.userinfoMapper.findIdNumberAll();

		// 执行数据插入操作 组装 UserDto
		for (int i = 0; i < excelVOList.size(); i++) {
			UserExcelVO excel = excelVOList.get(i);
			Set<String> errorMsg = new HashSet<>();
			// 校验用户名是否存在
			boolean exsitUserName = userList.stream()
					.anyMatch(sysUser -> excel.getUsername().equals(sysUser.getUsername()));

			if (exsitUserName) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, excel.getUsername()));
			}
			// 校验用户编号是否存在
			boolean exsitPersonNum = personNumList.stream()
					.anyMatch(personNum -> personNum.equals(excel.getPersonNum()));

			if (exsitPersonNum) {
				errorMsg.add(String.format("%s 用户编号已存在", excel.getPersonNum()));
			}
			// 校验身份证号是否存在
			boolean exsitIdNumber = idNumberList.stream()
					.anyMatch(idNum -> idNum.equals(excel.getIdNumber()));

			if (exsitIdNumber) {
				errorMsg.add(String.format("%s 身份证号已存在", excel.getIdNumber()));
			}

			if (!StringUtils.hasLength(excel.getHighestSchooling())){
				errorMsg.add("学历不能为空");
			}

			// 判断输入的部门名称列表是否合法
			Optional<SysDept> deptOptional = deptList.stream()
					.filter(dept -> excel.getDeptName().equals(dept.getName())).findFirst();
			if (!deptOptional.isPresent()) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_DEPT_DEPTNAME_INEXISTENCE, excel.getDeptName()));
			}

			// 判断输入的角色名称列表是否合法
			List<String> roleNameList = StrUtil.split(excel.getRoleNameList(), StrUtil.COMMA);
			List<SysRole> roleCollList = roleList.stream()
					.filter(role -> roleNameList.stream().anyMatch(name -> role.getRoleName().equals(name)))
					.collect(Collectors.toList());

			if (roleCollList.size() != roleNameList.size()) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_ROLENAME_INEXISTENCE, excel.getRoleNameList()));
			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				insertExcelUser(excel, deptOptional, roleCollList);
			}
			else {
				// 数据不合法情况
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}

		}

		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok(null, MsgUtils.getMessage(ErrorCodes.SYS_USER_IMPORT_SUCCEED));
	}

	@Override
	public List<Tree<Long>> selectTree() {
		// 查询全部部门
		List<SysUser> userList = baseMapper.selectList(Wrappers.emptyWrapper());
		// 查询数据权限内部门
		List<Long> userOwnIdList = baseMapper.selectListByScope(Wrappers.emptyWrapper(), new DataScope()).stream()
				.map(SysUser::getUserId).collect(Collectors.toList());

		List<SysUserinfo> userinfoList = this.userinfoMapper.selectListByScope(Wrappers.emptyWrapper(), new DataScope());
		// 权限内部门
		List<TreeNode<Long>> collect = userList.stream()
				.sorted(Comparator.comparing(SysUser::getCreateTime)).map(user -> {
					TreeNode<Long> treeNode = new TreeNode();
					treeNode.setId(user.getUserId());
					treeNode.setParentId(0L);
					treeNode.setName(user.getName());
					treeNode.setWeight(user.getCreateTime());
					// 有权限不返回标识
					Map<String, Object> extra = new HashMap<>(8);
					extra.put("isLock", !userOwnIdList.contains(user.getUserId()));
					extra.put("createTime", user.getCreateTime());
					extra.put("username", user.getUsername());
					extra.put("nickName", user.getNickname());
					extra.put("deptId", user.getDeptId());
					extra.put("deptName", user.getDeptName());
					extra.put("phone", user.getPhone());
					extra.put("leaderCode", user.getLeaderCode());
					extra.put("positionCode", user.getPositionCode());

					Optional<SysUserinfo> userInfoOptional = userinfoList.stream().filter(sysUserinfo -> Objects.equals(sysUserinfo.getUserId(), user.getUserId())).findFirst();
					if(userInfoOptional.isPresent()){
						SysUserinfo sysUserinfo = userInfoOptional.get();
						extra.put("deptFullName", sysUserinfo.getDeptFullname());
					}
					treeNode.setExtra(extra);
					return treeNode;
				}).collect(Collectors.toList());

		return TreeUtil.build(collect, 0L);
	}

	@Override
	public List<UserVO> selectUserVoByRoleId(Long roleId) {
		return baseMapper.getUserVoByRoleId(roleId);
	}

	@Override
	public List<SysUser> listByDeptIds(List<Long> deptIds) {
		LambdaQueryWrapper<SysUser> wrapper = Wrappers.<SysUser>query().lambda().in(SysUser::getDeptId, deptIds);
		List<SysUser> userList = this.list(wrapper);
		return Optional.ofNullable(userList).orElse(Lists.newArrayList());
	}

	/**
	 * 插入excel User
	 */
	private void insertExcelUser(UserExcelVO excel, Optional<SysDept> deptOptional, List<SysRole> roleCollList) {
		UserDTO userDTO = new UserDTO();
		userDTO.setUsername(excel.getUsername());
		userDTO.setPhone(excel.getPhone());
		userDTO.setNickname(excel.getNickname());
		userDTO.setName(excel.getName());
		userDTO.setEmail(excel.getEmail());
		// 批量导入初始密码为手机号
		userDTO.setPassword(userDTO.getPhone());
		// 初始化密码
		userDTO.setPassword("666666");
		// 根据部门名称查询部门ID
		userDTO.setDeptId(deptOptional.get().getDeptId());
		// 根据角色名称查询角色ID
		List<Long> roleIdList = roleCollList.stream().map(SysRole::getRoleId).collect(Collectors.toList());
		userDTO.setRole(roleIdList);
		SysUserinfo userinfo =new SysUserinfo();
		userinfo.setPersonNumber(excel.getPersonNum());
		userinfo.setName(excel.getRealName());
		userinfo.setLoginname(excel.getUsername());
		userinfo.setMobile(excel.getPhone());
		userinfo.setIdNumber(excel.getIdNumber());
		userinfo.setHukou(excel.getRegisterPermanentResidence());
		userinfo.setDegree(excel.getHighestSchooling());
		userinfo.setType(excel.getPersonnelType());
		userinfo.setPost(excel.getPost());
		userinfo.setProfesTitle(excel.getTitle());
		if (excel.getIdNumber().length() == 18){
			String year = excel.getIdNumber().substring(6,10);
			String month = excel.getIdNumber().substring(10,12);
			String day = excel.getIdNumber().substring(12,14);
			userinfo.setBirthday(LocalDate.of(Integer.parseInt(year), Month.of(Integer.parseInt(month)),Integer.valueOf(day)));
			String gender = String.valueOf(Integer.parseInt(excel.getIdNumber().substring(16,17)) % 2);
			userinfo.setGender(gender);
		}

		// 插入用户
		this.saveUser(userDTO,userinfo);
	}

	@Override
	public R<Boolean> registerUser(UserDTO userDto) {
		// 判断用户名是否存在
		SysUser sysUser = this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, userDto.getUsername()));
		if (sysUser != null) {
			String message = MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, userDto.getUsername());
			return R.failed(message);
		}
		return R.ok(saveUser(userDto));
	}


	/**
	 * 锁定用户
	 * @param username 用户名
	 * @return
	 */
	@Override
	@CacheEvict(value = CacheConstants.USER_DETAILS, key = "#username")
	public R<Boolean> lockUser(String username) {
		SysUser sysUser = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
		sysUser.setLockFlag(CommonConstants.STATUS_LOCK);
		baseMapper.updateById(sysUser);
		return R.ok();
	}

	@Override
	public List<SysUser> findByGroupCodeList(List<String> postCodeList) {
		return this.baseMapper.findByGroupCodeList(postCodeList);
	}

	@Override
	public List<SysUser> findUsesByUserNames(List<String> usernames) {
		List<SysUser> personals = Lists.newArrayList();
		if(CollUtil.isNotEmpty(usernames)) {
			LambdaQueryWrapper<SysUser> personalQueryWrapper = new LambdaQueryWrapper<>();
			personalQueryWrapper.in(SysUser::getUsername, usernames).eq(SysUser::getDelFlag, 0);
			personals = this.list(personalQueryWrapper);
		}
		return personals;
	}

	@Override
	public SysUser findUserByUserName(String username) {
		LambdaQueryWrapper<SysUser> personalQueryWrapper = new LambdaQueryWrapper<>();
		personalQueryWrapper.eq(SysUser::getUsername, username).eq(SysUser::getDelFlag, 0);
		return this.getOne(personalQueryWrapper);
	}

	@Override
	public boolean selectUserUpdatePasswordUserList() {
		LambdaQueryWrapper<SysUser> queryWrapper1 = new LambdaQueryWrapper<>();
		LambdaQueryWrapper<SysUser> queryWrapper2 = new LambdaQueryWrapper<>();

		List<SysUser> userList = Lists.newArrayList();

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DAY_OF_MONTH, -(ParamResolver.getInt("UPDATE_PASSWORD_DAY",90)));
		Date time = calendar.getTime();
		List<SysUser> list = this.list(queryWrapper1.isNull(SysUser::getUpdatePasswordDateTime));
		List<SysUser> list1 = this.list(queryWrapper2.le(SysUser::getUpdatePasswordDateTime, time));

		userList.addAll(list);
		userList.addAll(list1);

		if(CollUtil.isNotEmpty(userList)){
			// 发送系统信息
			String message = ParamResolver.getStr("UPDATE_PASSWORD_MESSAGE","您已经90天没有修改过密码，请尽快修改密码以防止密码泄露！");
			systemMessageRecordService.saveSystemMessageRecord(userList,message);
		}
		return CollUtil.isNotEmpty(userList);
	}
}
